package com.iou.view;

import java.sql.SQLException;

import com.iou.bean.IOUUser;
import com.iou.database.DatabaseHelper;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.server.ThemeResource;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

/**
 * The login screen.
 */
@SuppressWarnings("serial")
public class LoginView extends Panel implements View {

    /*
     * Class variables
     */
    private TextField userName;
    private PasswordField password;

    /**
     * Constructor.
     */
    public LoginView() {

        userName = new TextField("Username");
        userName.setWidth("100%");
        password = new PasswordField("Password");
        password.setWidth("100%");

        Embedded logo = new Embedded("", new ThemeResource("../IOUBoss.png"));
        setSizeFull();

        VerticalLayout contentField = new VerticalLayout();
        contentField.setWidth("50%");
        contentField.setHeight("220px");
        contentField.setSpacing(true);

        GridLayout grid = new GridLayout(4, 4);
        grid.addComponent(contentField, 1, 1, 2, 1);
        grid.setComponentAlignment(contentField, Alignment.MIDDLE_CENTER);
        grid.setSizeFull();
        setContent(grid);
        grid.addComponent(logo, 1, 0, 2, 0);
        grid.setComponentAlignment(logo, Alignment.MIDDLE_CENTER);

        contentField.addComponent(userName);
        contentField.addComponent(password);
        contentField.setComponentAlignment(userName, Alignment.BOTTOM_CENTER);
        contentField.setComponentAlignment(password, Alignment.BOTTOM_CENTER);

        HorizontalLayout buttonField = new HorizontalLayout();
        buttonField.setWidth("100%");
        buttonField.setSpacing(true);
        contentField.addComponent(buttonField);
        contentField
                .setComponentAlignment(buttonField, Alignment.MIDDLE_CENTER);

        Label vasenFillLabel = new Label("");
        vasenFillLabel.setWidth("100%");
        grid.addComponent(vasenFillLabel, 0, 2, 0, 3);

        Label oikeaFillLabel = new Label("");
        oikeaFillLabel.setWidth("100%");
        grid.addComponent(oikeaFillLabel, 3, 2, 3, 3);

        final VerticalLayout labelLayout = new VerticalLayout();
        labelLayout.setSizeFull();
        grid.addComponent(labelLayout, 0, 0);

        /*
         * Validates the entered username and password and navigates to users
         * mainmenu if everything is fine. Requirements: username&&password
         * matches to a username-password pair fetched from the database.
         */
        Button login = new Button("Login");
        login.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                try {
                    if (DatabaseHelper.validateUser(userName.getValue(),
                            password.getValue()) != null) {
                        Notification.show("Login OK!",
                                Notification.Type.TRAY_NOTIFICATION);
                        IouUI.getCurrent()
                                .getNavigator()
                                .addView(
                                        "ListView",
                                        new ListView(DatabaseHelper
                                                .validateUser(
                                                        userName.getValue(),
                                                        password.getValue())));
                        IouUI.getCurrent()
                                .getNavigator()
                                .addView(
                                        "MainMenuView",
                                        new MainMenuView(DatabaseHelper
                                                .validateUser(
                                                        userName.getValue(),
                                                        password.getValue())));
                        userName.setValue("");
                        password.setValue("");
                        IouUI.getCurrent().getNavigator()
                                .navigateTo("MainMenuView");
                    } else {

                        Notification
                                .show("Invalid password and/or username",
                                        "Please try again with a different password and/or username",
                                        Notification.Type.ERROR_MESSAGE);
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        /*
         * "Help" button.
         */
        Button helpButton = new Button("Help");
        helpButton.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                Window mywindow = new Window("Help");
                UI.getCurrent().addWindow(mywindow);
                AbsoluteLayout windowLayout = new AbsoluteLayout();
                mywindow.center();
                mywindow.setHeight("400px");
                mywindow.setWidth("400px");
                mywindow.setModal(true);
                mywindow.setResizable(false);
                mywindow.setContent(windowLayout);

                Label label = new Label(
                        "IOU Boss is a small Vaadin application that was made to make the management of IOU notes easier.");
                Label label2 = new Label(
                        "Well what is an IOU note then...? From Wikipedia: \"An IOU (abbreviated from the phrase \"I owe you\") is usually an informal document acknowledging debt. An IOU differs from a promissory note in that an IOU is not a negotiable instrument and does specify repayment terms such as the time of repayment. IOUs usually specify the debtor, the amount owed, and sometimes the creditor.\" UOMe stands for - you guessed it - \"You owe me\", and is meant to be used when someone owes you money.");
                Label label3 = new Label(
                        "The idea behind the application is that you can create IOU notes that contain info about the IOU (i.e. amount of money involved, date, participant…) and save them into your account. The app will show all notes that you've created in a handy table, from which you can also edit them and mark them as \"completed\" (via double clicking on the note in the table). Handy for remembering those small loans you're giving to your friends every night at a bar!");

                windowLayout.addComponent(label, "top:10px; left:10px");
                windowLayout.addComponent(label2, "top:55px; left:10px");
                windowLayout.addComponent(label3, "top:210px; left:10px");

            }
        });

        /*
         * Validates the entered username and password and registers a new user
         * if everything is fine. Requirements: username!=password,
         * username&&password != "", username not in use
         */
        Button register = new Button("Register");
        register.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                try {
                    if (DatabaseHelper.userDao.queryForId(userName.getValue()) == null) {
                        if (password.getValue().isEmpty()
                                || userName.getValue().isEmpty()) {
                            Notification.show(
                                    "Username or password field empty",
                                    "Please enter a password or a username",
                                    Notification.Type.ERROR_MESSAGE);
                        } else {

                            if (userName.getValue().equals(password.getValue())) {
                                Notification
                                        .show("Password can't be identical to the username",
                                                "Please enter a different password",
                                                Notification.Type.ERROR_MESSAGE);
                            } else {
                                IOUUser newUser = new IOUUser(userName
                                        .getValue(), password.getValue());
                                try {
                                    DatabaseHelper.storeUser(newUser);
                                } catch (SQLException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                Notification.show("Created a new user: "
                                        + userName.getValue(),
                                        Notification.Type.TRAY_NOTIFICATION);
                                // userName.setValue("");
                                // password.setValue("");
                            }
                        }
                    } else {
                        Notification.show("Username already in use!",
                                "Please try a different username",
                                Notification.Type.ERROR_MESSAGE);
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        buttonField.addComponent(login);
        login.setWidth("100%");
        buttonField.addComponent(register);
        register.setWidth("100%");

        HorizontalLayout fillOut = new HorizontalLayout();
        contentField.addComponent(fillOut);
        fillOut.setHeight("70px");

        HorizontalLayout helpField = new HorizontalLayout();
        helpField.setWidth("100%");
        helpField.setSpacing(true);
        contentField.addComponent(helpField);

        helpField.addComponent(helpButton);
        helpButton.setWidth("100%");

        grid.setColumnExpandRatio(0, 8);
        grid.setColumnExpandRatio(1, 1);
        grid.setColumnExpandRatio(2, 1);
        grid.setColumnExpandRatio(3, 8);

        grid.setRowExpandRatio(0, 1);
        grid.setRowExpandRatio(1, 3);
        grid.setRowExpandRatio(2, 3);
        grid.setRowExpandRatio(3, 3);

        userName.focus();
        login.setClickShortcut(KeyCode.ENTER);

    }

    @Override
    public void enter(ViewChangeEvent event) {
    }
}